package com.hs.framework.utils

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object HashUtils {

    const val salt : String = "HSKJAndroid"
    /**
     * 计算输入字符串的SHA-256哈希值
     */
    fun sha256(input: String): String {
        return hash(input + salt, "SHA-256")
    }

    /**
     * 计算输入字符串的SHA-1哈希值
     */
    fun sha1(input: String): String {
        return hash(input + salt, "SHA-1")
    }

    /**
     * 计算输入字符串的MD5哈希值
     */
    fun md5(input: String): String {
        return hash(input + salt, "MD5")
    }

    private fun hash(input: String, algorithm: String): String {
        try {
            val md = MessageDigest.getInstance(algorithm)
            val digest = md.digest(input.toByteArray())
            val hexString = StringBuilder()
            for (b in digest) {
                val hex = Integer.toHexString(0xff and b.toInt())
                if (hex.length == 1) hexString.append('0')
                hexString.append(hex)
            }
            return hexString.toString()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
            return ""
        }
    }
}